package com.hmdp.service.impl;

import cn.hutool.core.bean.BeanUtil;
import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.hmdp.dto.Result;
import com.hmdp.dto.UserDTO;
import com.hmdp.entity.Follow;
import com.hmdp.mapper.FollowMapper;
import com.hmdp.service.IFollowService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hmdp.service.IUserService;
import com.hmdp.utils.UserHolder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import java.util.Collections;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;

import static com.hmdp.utils.RedisConstants.FOLLOWS_KEY;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 */
@Service
public class FollowServiceImpl extends ServiceImpl<FollowMapper, Follow> implements IFollowService {


    @Autowired
    StringRedisTemplate stringRedisTemplate;
    @Autowired
    IUserService userService;

    /**
     * 关注或取消关注
     * @param followUserId
     * @param isFollow
     * @return
     */
    @Override
    public Result follow(Long followUserId, Boolean isFollow) {


        //1.获取登录用户
        Long userId = UserHolder.getUser().getId();
        String key = FOLLOWS_KEY + userId;
        //2.判断是关注还是取关
        if(isFollow){
            //2.1关注就新增数据
            Follow follow = new Follow();
            follow.setUserId(userId);
            follow.setFollowUserId(followUserId);
            boolean isSuccess = save(follow);
            if(isSuccess){
             stringRedisTemplate.opsForSet().add(key,followUserId.toString());
            }
        }else{
            //3.取关，则在数据库中删除 delete from tb_follow where user_id = ?
            // &&follow_user_id = ?;
            boolean isSuccess = remove(new QueryWrapper<Follow>()
                    .eq("user_id", userId)
                    .eq("follow_user_id", followUserId));
            if(isSuccess){
                stringRedisTemplate.opsForSet().remove(key,followUserId.toString());
            }
        }
        return Result.ok();
    }

    /**
     * 是否关注用户
     * @param followUserId
     * @return
     */
    @Override
    public Result isFollow(Long followUserId) {
        //1.获取当前登录的用户
        Long userId = UserHolder.getUser().getId();
        //2.查询是否关注 select count(*) from tb_follow where user_id=userId
        //&& follow_user_id =followUserId
        Long count = query().eq("user_id", userId)
                .eq("follow_user_id", followUserId).count();
       //3.判断是否关注
        return Result.ok(count>0 );

    }

    @Override
    public Result followCommons(Long id) {
        //1.获取当前登录用户的id
        Long userId = UserHolder.getUser().getId();
        String key = FOLLOWS_KEY + userId;
        String key2 = FOLLOWS_KEY + id;
        //2.求他们的交集即为共同关注

        Set<String> commons = stringRedisTemplate.opsForSet().intersect(key, key2);

        if( commons==null || commons.isEmpty()){
            return Result.ok(Collections.emptyList());
        }

        Set<Long> ids = commons.stream().map(Long::valueOf).collect(Collectors.toSet());

        List<UserDTO> userDTOS = userService.listByIds(ids)
                .stream().map(user -> BeanUtil.copyProperties(user, UserDTO.class)).collect(Collectors.toList());

        return Result.ok(userDTOS);
    }
}
